package com.jade.zsy.purchase.facade.impl;

import com.jade.bss.DbException;
import com.jade.bss.base.RoleAction;
import com.jade.bss.base.customer.Customer;
import com.jade.bss.base.utils.CopyBean;
import com.jade.bss.base.utils.MsgUtil;
import com.jade.bss.db.impl.BaseFacadeImpl;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.base.util.PagingResult;
import com.jade.zsy.base.common.StatusConstant;
import com.jade.zsy.base.entity.BusinessCode;
import com.jade.zsy.base.entity.Partner;
import com.jade.zsy.base.entity.Sku;
import com.jade.zsy.base.entity.Warehouse;
import com.jade.zsy.base.facade.BusinessCodeFacade;
import com.jade.zsy.base.facade.PartnerFacade;
import com.jade.zsy.base.facade.SkuFacade;
import com.jade.zsy.base.facade.WarehouseFacade;
import com.jade.zsy.purchase.dao.PODao;
import com.jade.zsy.purchase.entity.PO;
import com.jade.zsy.purchase.entity.PODetail;
import com.jade.zsy.purchase.service.PODetailFacade;
import com.jade.zsy.purchase.service.POFacade;
import com.jade.zsy.purchase.vo.PODetailVo;
import com.jade.zsy.purchase.vo.POVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;

/**
 * 员工信息表
 * User: jinya
 * Date: 2017/5/31
 * Time: 11:07
 * TEL :17701640710   MAIL:2009_jinya@163.com
 * To change this template use File | Settings | File Templates.
 */
@Service("POFacade")
public class PoFacadeImpl extends BaseFacadeImpl implements POFacade {
    private BusinessCodeFacade businessCodeFacade = ApplicationContextUtils.getBean("BusinessCodeFacade");
    private WarehouseFacade warehouseFacade = ApplicationContextUtils.getBean("WarehouseFacade");
    private PartnerFacade partnerFacade = ApplicationContextUtils.getBean("PartnerFacade");
    private PODetailFacade poDetailFacade = ApplicationContextUtils.getBean("PODetailFacade");
    private SkuFacade skuFacade = ApplicationContextUtils.getBean("SkuFacade");
    @Inject
    @Named("PODao")
    private PODao entityDao;
    @Override
    @Transactional
    public void save(POVo entity) throws Exception {
        if(entity.getDetailVoList()==null || entity.getDetailVoList().size()<=0){
            throw new DbException("NO_DETAIL", "明细不能为空");
        }
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isEmpty(entity.getPono()))//用户自定义为空系统自动生成
            entity.setPono(businessCodeFacade.nextBusinessCode(BusinessCode.KEY_BASE_ORG));
        entity.setOwnerId(customer.getOwnerId());
        entity.setCreator(customer.getNickName());
        entity.setCreatorId(customer.getId());
        entity.setStatus(StatusConstant.RECORD_NORMAL);
        PO po = CopyBean.copy(entity, PO.class); 
        //检查供应商状态是否正常
        if(po.getSupplierId()<=0)  throw new DbException("NO_DETAIL","请选择有效供应商");
        Partner partner=partnerFacade.getById(Partner.class,po.getSupplierId());
        if(partner==null || partner.getStatus()!= StatusConstant.RECORD_NORMAL){
            throw new DbException("NO_DETAIL","请选择有效供应商或者供应商已经停用");
        }
        po.setDeliverAddress(partner.getAddress());
        po.setDeliverMobile(partner.getTel());
        po.setSupplierName(partner.getName());
        super.save(po);
        //检查是否存在明细
        List<PODetail> poDetailList=new ArrayList<PODetail>();
         for(PODetailVo detailVo : entity.getDetailVoList()){
             Sku sku=skuFacade.getById(Sku.class,detailVo.getSkuId());
             if(sku==null || sku.getStatus()!= StatusConstant.RECORD_NORMAL){
                 throw new DbException("NO_DETAIL", "商品不存在或者商品已下架");
             }
             //检查仓库是否可用
             if(detailVo.getWarehouseId()>0){
                 Warehouse warehouse=warehouseFacade.getById(Warehouse.class,detailVo.getWarehouseId());
                 if(warehouse==null || warehouse.getStatus()!= StatusConstant.RECORD_NORMAL){
                     throw new DbException("NO_DETAIL","状态异常或者不存在");
                 }
             }


             PODetail detail = CopyBean.copy(detailVo, PODetail.class);
             detail.setPoId(po.getId());
             detail.setSkucode(sku.getSkuCode());
             detail.setPono(po.getPono());
             detail.setOwnerId(customer.getOwnerId());
             detail.setCreator(customer.getNickName());
             detail.setCreatorId(customer.getId());
             entity.setTotalQty(detail.getQty()+entity.getTotalQty());
             poDetailList.add(detail);
         }
        poDetailFacade.batchSave(poDetailList);
    }
    @Override
    @Transactional
    public void update(Object obj) throws DbException {
        PO entity=(PO)obj;
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        entity.setModifier(customer.getTrueName());
        super.update(entity);
    }

    @Transactional
    public void delete(long... obj) throws DbException {
        for(long id : obj){
            PO org=entityDao.getById(PO.class,id);
            if(org==null || org.getId()<=0)
                throw new DbException(MsgUtil.RECODRD_NO, MsgUtil.RECODRD_NO_TEXT);
            entityDao.delete(PO.class,org);
        }
    }

    @Transactional
    public void disabled(long... obj) throws DbException {
        for(long id : obj){
            PO org=entityDao.getById(PO.class,id);
            if(org==null || org.getId()<=0)
                throw new DbException(MsgUtil.RECODRD_NO, MsgUtil.RECODRD_NO_TEXT);
            org.setStatus(StatusConstant.RECORD_STOP);
            entityDao.update(org);
        }
    }

    @Transactional
    public void enabled(long... obj) throws DbException {
        for(long id : obj){
            PO enPO=entityDao.getById(PO.class,id);
            if(enPO==null || enPO.getId()<=0)
                throw new DbException(MsgUtil.RECODRD_NO, MsgUtil.RECODRD_NO_TEXT);
            enPO.setStatus(StatusConstant.RECORD_NORMAL);
            entityDao.update(enPO);
        }
    }

    @Override
    public PagingResult queryEntity(Object obj, int page, int size, String keyword, String... orders) throws DbException,IllegalAccessException, InstantiationException {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        POVo entity=(POVo)obj;
        Criteria criteria = new Criteria((page - 1) * size, size);
        criteria.add(Restrictions.eq("ownerId",customer.getOwnerId()));
        if(StringUtils.isNotEmpty(keyword)){
            criteria.add(Restrictions.or(Restrictions.like("code", keyword), Restrictions.like("name", keyword)));
        }
        criteria.addOrder(com.jade.framework.base.criterion.Order.desc(RoleAction.SORT_ITEM));
        PagingList pagingList = entityDao.queryEntity(PO.class, criteria);
        PagingResult result = PagingResult.getResult(CopyBean.copy(pagingList, POVo.class), pagingList.getTotalCount(), page, size);
        return result;
    }
}
